const { app, BrowserWindow, ipcMain, dialog, globalShortcut } = require('electron')
const path = require('path')

const createWindow = () => {
    const win = new BrowserWindow({
      width: 800,
      height: 600,
      minWidth: 800,
      minHeight: 600,
      titleBarStyle: 'hidden',
      backgroundColor: 'rgba(23, 24, 43, .5)',
      titleBarOverlay: false,
      transparent: true,
      webPreferences: {
        webSecurity: false, 
        preload: path.join(__dirname, 'preload.js'),
      }
    }); 

    if(process.env.npm_lifecycle_event && process.env.npm_lifecycle_event.indexOf('dev') > -1) {
      win.loadURL('http://localhost:8611')
    } else {
      win.loadFile('./dist/index.html')
    }
    return win
  }

  app.whenReady().then(() => {
    let mainWin = createWindow()

    globalShortcut.register('F12', () => {
      mainWin.webContents.toggleDevTools()
    })

    //切换开发者模式
    ipcMain.on('devtools:toggle', () => {
        mainWin.webContents.toggleDevTools()
    })

    //主窗口关闭
    ipcMain.on('win:close', () => {
      mainWin.close()
    })
    //放大窗口
    ipcMain.handle('win:max', () => {
      if (!mainWin.isMaximized())  {
        mainWin.maximize()
      } else {
        mainWin.unmaximize()
      }
      return mainWin.isMaximized()
    })
    //缩小窗口
    ipcMain.on('win:min', () => {
      mainWin.minimize()
    })
    //打开文件
    ipcMain.handle('dialog:open', showOpenDialog)

    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
      }
    }); 


  })

  app.on('will-quit', () => {
    globalShortcut.unregister('F12')
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
  })

  //打开文件或者文件夹
  /**
   * 
   * @param {*} type openFile | openDirectory 打开文件或者文件夹
   * @returns 
   */
  const showOpenDialog = async (event, type = 'openFile') => {
    const {canceled, filePaths} = await dialog.showOpenDialog({
      properties: [type]
    })
    if (canceled) return
    return filePaths[0]
  }